/**
 * 
 */
package com.hs.core.index;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;

import com.hs.HsBase;
import com.hs.core.db.DBOperator;
import com.hs.core.db.DatabaseConnection;
import com.hs.pre.model.PreEntry;
import com.hs.utils.DateUtil;

/**
 * @author shl
 *
 */
public  class IndexFacade {
	 public static final String LINE_SEP = System.getProperty("line.separator");
	 private static SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
	 private static SimpleDateFormat solrFormatter =
	            new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.US);
	/**
	 * 获得request
	 * @return
	 */
	public HttpServletRequest getHttpServletRequest(){
		WebContext ctx = WebContextFactory.get();   
		return ctx.getHttpServletRequest();   
	}
	/**
	 * 获得session
	 * @return
	 */
	public HttpSession getHttpSession(){
		WebContext ctx = WebContextFactory.get();   
		return ctx.getSession();   
	}
	
	/**
	 * 重做索引
	 */
	public String indexAll(){
		String message = "";
		try {
			
			List preList = new ArrayList();
			DBOperator dbo = DatabaseConnection.getDBOperator();
			List list = dbo.select(HsBase.getAnsiSqlMap().get("preinfo.select_all")+"", null);
			System.out.println("list；" + list.size());
		    for(int j = 0;j<list.size();j++){
		    	PreEntry entry = new PreEntry((Map)list.get(j)); 
		    	boolean flag =indexPre(entry);
		    	System.out.println(flag);
		    	//preList.add(entry);
		    }
		    
		    message =  addIndex(preList);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return message;
	}
	public boolean indexPre(PreEntry entry){
		boolean  flag = true;
		StringBuilder builder = new StringBuilder();
		StringBuilder  command = new StringBuilder(""); 
		if(null != entry){
			command.append("<add>").append(LINE_SEP); 
			DBOperator dbo = null;
			try {
				dbo = DatabaseConnection.getDBOperator();
			} catch (Exception e) { 
				e.printStackTrace();
			} 
			if(null != entry){ 
					//索引完成后更新索引的状态及索引时间
				System.out.println("entry.getId():" + entry.getId());
					dbo.update(HsBase.getAnsiSqlMap().get("preinfo.update")+"", new Object[]{"02",DateUtil.GetDate(),entry.getId()});
					command.append("<doc>").append(LINE_SEP);
					command.append("<field name=\"id\">").append(entry.getId()).append("</field>").append(LINE_SEP);
					command.append("<field name=\"fangm\">").append(entry.getFangm()).append("</field>").append(LINE_SEP);
					if (entry.getBiem() != null && entry.getBiem().equals("") == false&& entry.getBiem().equalsIgnoreCase("null") == false)
					{
					   command.append("<field name=\"biem\">").append(entry.getBiem()).append("</field>").append(LINE_SEP);
					}
					if (entry.getChufly() != null && entry.getChufly().equals("") == false&& entry.getChufly().equalsIgnoreCase("null") == false)
					{
					   command.append("<field name=\"chufly\">").append(entry.getChufly()).append("</field>").append(LINE_SEP);
					}
					if (entry.getYaowzc() != null && entry.getYaowzc().equals("") == false&& entry.getYaowzc().equalsIgnoreCase("null") == false)
					{
					   command.append("<field name=\"yaowzc\">").append(entry.getYaowzc()).append("</field>").append(LINE_SEP);
					}
					if (entry.getJiaj() != null && entry.getJiaj().equals("") == false&& entry.getJiaj().equalsIgnoreCase("null") == false)
					{
					   command.append("<field name=\"jiaj\">").append(entry.getJiaj()).append("</field>").append(LINE_SEP);
					}
					if (entry.getGongx() != null && entry.getGongx().equals("") == false&& entry.getGongx().equalsIgnoreCase("null") == false)
					{
					   command.append("<field name=\"gongx\">").append(entry.getGongx()).append("</field>").append(LINE_SEP);
					}
					if (entry.getZhuz() != null && entry.getZhuz().equals("") == false&& entry.getZhuz().equalsIgnoreCase("null") == false)
					{
					   command.append("<field name=\"zhuz\">").append(entry.getZhuz()).append("</field>").append(LINE_SEP);
					}
					if (entry.getZhibff() != null && entry.getZhibff().equals("") == false&& entry.getZhibff().equalsIgnoreCase("null") == false)
					{
					   command.append("<field name=\"zhibff\">").append(entry.getZhibff()).append("</field>").append(LINE_SEP);
					}
					if (entry.getYongfyl() != null && entry.getYongfyl().equals("") == false&& entry.getYongfyl().equalsIgnoreCase("null") == false)
					{
					   command.append("<field name=\"yongfyl\">").append(entry.getYongfyl()).append("</field>").append(LINE_SEP);
					}
					if (entry.getYongyjj() != null && entry.getYongyjj().equals("") == false&& entry.getYongyjj().equalsIgnoreCase("null") == false)
					{
					   command.append("<field name=\"yongyjj\">").append(entry.getYongyjj()).append("</field>").append(LINE_SEP);
					}
					if (entry.getLincyy() != null && entry.getLincyy().equals("") == false&& entry.getLincyy().equalsIgnoreCase("null") == false)
					{
					   command.append("<field name=\"lincyy\">").append(entry.getLincyy()).append("</field>").append(LINE_SEP);
					}
					if (entry.getYaolzy() != null && entry.getYaolzy().equals("") == false&& entry.getYaolzy().equalsIgnoreCase("null") == false)
					{
					   command.append("<field name=\"yaolzy\">").append(entry.getYaolzy()).append("</field>").append(LINE_SEP);
					}
					if (entry.getGejls() != null && entry.getGejls().equals("") == false&& entry.getGejls().equalsIgnoreCase("null") == false)
					{
					   command.append("<field name=\"gejls\">").append(entry.getGejls()).append("</field>").append(LINE_SEP);
					}
					if (entry.getBeiz() != null && entry.getBeiz().equals("") == false&& entry.getBeiz().equalsIgnoreCase("null") == false)
					{
					   command.append("<field name=\"beiz\">").append(entry.getBeiz()).append("</field>").append(LINE_SEP);
					}
					command.append("</doc>").append(LINE_SEP);
				}
			}
			command.append("</add>").append(LINE_SEP); 
		 
		try {
			processAdd(command.toString());
			processCommit();
		} catch (ServletException e) { 
			flag = false;
			e.printStackTrace();
		} catch (IOException e) {
			flag = false;
			e.printStackTrace();
		}    
		return flag;
	}
	/**
	 * 添加索引
	 * @param entry
	 * @return
	 */
	public String addIndex(List preList){
		String message = "";
		StringBuilder builder = new StringBuilder();
		StringBuilder  command = new StringBuilder(""); 
		if(null != preList){
			command.append("<add>").append(LINE_SEP); 
			DBOperator dbo = null;
			try {
				dbo = DatabaseConnection.getDBOperator();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			for( int i =0;i<preList.size();i++){
				PreEntry entry = (PreEntry)preList.get(i);
				if(null != entry){
					builder.append(entry.getId());
					builder.append("@");
					builder.append(DateUtil.GetDate());
					builder.append("@");
					builder.append("已索引");
					builder.append(",");
					//索引完成后更新索引的状态及索引时间
					System.out.println("entry.getId():" + entry.getId());
					dbo.update(HsBase.getAnsiSqlMap().get("preinfo.update")+"", new Object[]{"02",DateUtil.GetDate(),entry.getId()});
					command.append("<doc>").append(LINE_SEP);
					command.append("<field name=\"id\">").append(entry.getId()).append("</field>").append(LINE_SEP);
					command.append("<field name=\"fangm\">").append(entry.getFangm()).append("</field>").append(LINE_SEP);
					if (entry.getBiem() != null && entry.getBiem().equals("") == false&& entry.getBiem().equalsIgnoreCase("null") == false)
					{
					   command.append("<field name=\"biem\">").append(entry.getBiem()).append("</field>").append(LINE_SEP);
					}
					if (entry.getChufly() != null && entry.getChufly().equals("") == false&& entry.getChufly().equalsIgnoreCase("null") == false)
					{
					   command.append("<field name=\"chufly\">").append(entry.getChufly()).append("</field>").append(LINE_SEP);
					}
					if (entry.getYaowzc() != null && entry.getYaowzc().equals("") == false&& entry.getYaowzc().equalsIgnoreCase("null") == false)
					{
					   command.append("<field name=\"yaowzc\">").append(entry.getYaowzc()).append("</field>").append(LINE_SEP);
					}
					if (entry.getJiaj() != null && entry.getJiaj().equals("") == false&& entry.getJiaj().equalsIgnoreCase("null") == false)
					{
					   command.append("<field name=\"jiaj\">").append(entry.getJiaj()).append("</field>").append(LINE_SEP);
					}
					if (entry.getGongx() != null && entry.getGongx().equals("") == false&& entry.getGongx().equalsIgnoreCase("null") == false)
					{
					   command.append("<field name=\"gongx\">").append(entry.getGongx()).append("</field>").append(LINE_SEP);
					}
					if (entry.getZhuz() != null && entry.getZhuz().equals("") == false&& entry.getZhuz().equalsIgnoreCase("null") == false)
					{
					   command.append("<field name=\"zhuz\">").append(entry.getZhuz()).append("</field>").append(LINE_SEP);
					}
					if (entry.getZhibff() != null && entry.getZhibff().equals("") == false&& entry.getZhibff().equalsIgnoreCase("null") == false)
					{
					   command.append("<field name=\"zhibff\">").append(entry.getZhibff()).append("</field>").append(LINE_SEP);
					}
					if (entry.getYongfyl() != null && entry.getYongfyl().equals("") == false&& entry.getYongfyl().equalsIgnoreCase("null") == false)
					{
					   command.append("<field name=\"yongfyl\">").append(entry.getYongfyl()).append("</field>").append(LINE_SEP);
					}
					if (entry.getYongyjj() != null && entry.getYongyjj().equals("") == false&& entry.getYongyjj().equalsIgnoreCase("null") == false)
					{
					   command.append("<field name=\"yongyjj\">").append(entry.getYongyjj()).append("</field>").append(LINE_SEP);
					}
					if (entry.getLincyy() != null && entry.getLincyy().equals("") == false&& entry.getLincyy().equalsIgnoreCase("null") == false)
					{
					   command.append("<field name=\"lincyy\">").append(entry.getLincyy()).append("</field>").append(LINE_SEP);
					}
					if (entry.getYaolzy() != null && entry.getYaolzy().equals("") == false&& entry.getYaolzy().equalsIgnoreCase("null") == false)
					{
					   command.append("<field name=\"yaolzy\">").append(entry.getYaolzy()).append("</field>").append(LINE_SEP);
					}
					if (entry.getGejls() != null && entry.getGejls().equals("") == false&& entry.getGejls().equalsIgnoreCase("null") == false)
					{
					   command.append("<field name=\"gejls\">").append(entry.getGejls()).append("</field>").append(LINE_SEP);
					}
					if (entry.getBeiz() != null && entry.getBeiz().equals("") == false&& entry.getBeiz().equalsIgnoreCase("null") == false)
					{
					   command.append("<field name=\"beiz\">").append(entry.getBeiz()).append("</field>").append(LINE_SEP);
					}
					command.append("</doc>").append(LINE_SEP);
				}
			}
			command.append("</add>").append(LINE_SEP); 
		} 
		try {
			message = processAdd(command.toString());
			processCommit();
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			message = "添加索引异常";
			e.printStackTrace();
		}  
		message = builder.toString();
		//ParseXml p = new ParseXml(message);
		 //message = "索引更新成功";
		return message;
		
	}
	/**
	 * 更新索引
	 * @param entry
	 * @return
	 */
	public String updateIndex(List preList){
		String message = "";
//		if(null != entry && "".equals(entry.get("id"))){
//			deleteIndex((String)entry.get("id"));
//			addIndex(entry);
//		} 
		return message;
		
	}
	/**
	 * 删除索引
	 * @param indexKey
	 * @return
	 */
	public String deleteIndex(String delStr){
		String message = "";
		
		if(null != delStr && !"".equals(delStr)&&!"null".equalsIgnoreCase(delStr)){
			String[] ids = delStr.split(",");
			if(null != ids && ids.length >0){
				for(int i = 0;i<ids.length;i++){ 
					DBOperator dbo = null;
					try {
						dbo = DatabaseConnection.getDBOperator();
					} catch (Exception e) { 
						e.printStackTrace();
					}
					if(null != ids[i])
						try {
							processDelete(ids[i]);
							//删除索引后更新方剂的索引状态和时间
							dbo.update(HsBase.getAnsiSqlMap().get("preinfo.update")+"", new Object[]{"01",DateUtil.GetDate(),ids[i]});
						} catch (IOException e) {
							 message = "索引删除失败【"+ ids[i] + "】";
						} catch (ServletException e) {
							message = "索引删除失败【"+ ids[i] + "】";
						}
				}
			}
			
		}
		try {
			processCommit();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		message = "删除索引成功";
		return message;
	}
	/**
     * Delete by ID.  This app does not support delete by query at this point, even though Solr does.
     * @param request
     * @param response
     * @throws IOException
     * @throws ServletException
     */
    private String processDelete(String indexKey) throws IOException, ServletException
    {
        
        String command = "<delete>" + LINE_SEP +
                "<id>" + indexKey + LINE_SEP
                + "</id></delete>";

        return processSubmitCommand(command);

    }
    /**
     * Create an add command, made up of fields in a document.
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private String processAdd(String command)
            throws ServletException, IOException
    { 
        return processSubmitCommand(command);
    }
    /**
     * Create an optimize command to send to Solr and display it on the SHOW_XMLCOMMAND_JSP page
     *
     * @param request
     * @param response
     * @throws IOException
     * @throws ServletException
     */
    private String processOptimizeCommand() throws IOException, ServletException
    {
        String command = "<optimize/>";

        return processSubmitCommand(command);
    }
    /**
     * Create a commit command
     *
     * @param request
     * @param response
     * @throws IOException
     * @throws ServletException
     */
    private String processCommit()
            throws IOException, ServletException
    {
        String command = "<commit/>";
        return processSubmitCommand(command);
    }
    
    /**
     * Sumbit a Post Command, and then forward to {@link #SHOW_SOLR_RESULTS_JSP}
     * @param request
     * @param response
     * @param command
     * @throws IOException
     * @throws ServletException
     */
    private String processSubmitCommand(String command)
            throws IOException, ServletException
    {   
//    	HttpServletRequest request = getHttpServletRequest();
//    	String path = request.getContextPath();
//    	String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
//    	System.out.println("basePath:" + basePath);
        //String results = sendPostCommand(command, basePath + "/update");
        String results = sendPostCommand(command, "http://localhost:8081/pre/update");

        return results;
    }
	/**
     * Send the command to Solr using a Post
     *
     * @param command
     * @param url
     * @return
     * @throws IOException
     */
    private String sendPostCommand(String command, String url)
            throws IOException
    {
        String results = null;
        HttpClient httpClient = new HttpClient();

        PostMethod post = new PostMethod(url); 
        RequestEntity re = new StringRequestEntity(command, "text/xml", "UTF-8");
        post.setRequestEntity(re);
        try
        {
            // Execute the method.
            int statusCode = httpClient.executeMethod(post);

            if (statusCode != HttpStatus.SC_OK)
            {
                System.err.println("Method failed: " + post.getStatusLine());
            }

            // Read the response body.
            byte[] responseBody = post.getResponseBody();

            // Deal with the response.
            // Use caution: ensure correct character encoding and is not binary data
            results = new String(responseBody);
        }
        catch (HttpException e)
        {
            System.err.println("Fatal protocol violation: " + e.getMessage());
            e.printStackTrace();
        }
        catch (IOException e)
        {
            System.err.println("Fatal transport error: " + e.getMessage());
            e.printStackTrace();
        }
        finally
        {
            // Release the connection.
            post.releaseConnection();
        }
        return results;
    }
    /**
     * Send the command to Solr using a GET
     * @param queryString
     * @param url
     * @return
     * @throws IOException
     */
    private String sendGetCommand(String queryString, String url)
            throws IOException
    {
        String results = null;
        HttpClient client = new HttpClient();
        GetMethod get = new GetMethod(url);
        get.setQueryString(queryString.trim());

        client.executeMethod(get);
        try
        {
            // Execute the method.
            int statusCode = client.executeMethod(get);

            if (statusCode != HttpStatus.SC_OK)
            {
                System.err.println("Method failed: " + get.getStatusLine());
            }

            // Read the response body.
            byte[] responseBody = get.getResponseBody();

            // Deal with the response.
            // Use caution: ensure correct character encoding and is not binary data
            results = new String(responseBody);
        }
        catch (HttpException e)
        {
            System.err.println("Fatal protocol violation: " + e.getMessage());
            e.printStackTrace();
        }
        catch (IOException e)
        {
            System.err.println("Fatal transport error: " + e.getMessage());
            e.printStackTrace();
        }
        finally
        {
            // Release the connection.
            get.releaseConnection();
        }
        return results;
    }

    /**
     * Only add space to the query if there is already something in the query.
     * @param query
     */
    private void addSpaceToQuery(StringBuilder query)
    {
        if (query.length() > 0)
        {
            //Use a + sign for URL Encoding
            query.append('+');
        }
    }

    private boolean isShowCommand(HttpServletRequest request)
    {
        boolean result = false;
        String tmp = request.getParameter("showCommand");
        result = Boolean.parseBoolean(tmp);

        return result;
    }

}
